var ACTDEFS ="defs/actions.xml";
var ACTSFILE="data/actions.xml";
var ACTSDOM=new ActiveXObject("Msxml2.DOMDocument");
var ACTSROOT="";

var ACTSTYPES=new Array();
var ACTSRWDS = new Array();
var ACTSTRWDS= new Array();

// Initialize arrays from defs file
var ACTSDEFSDOM = new ActiveXObject("Msxml2.DOMDocument");

if(!ACTSDOM  || !ACTSDEFSDOM) {
  alert("Error creating object XMLACTIONS");
}

ACTSDEFSDOM.load(ACTDEFS);
ACTSDEFSROOT=ACTSDEFSDOM.selectSingleNode('actions');
for(var node=0; node < ACTSDEFSROOT.childNodes.length; node++) {
  //alert(ACTSDEFSROOT.childNodes[node].getAttribute("name"));
  if(!ACTSDEFSROOT.childNodes[node].getAttribute("ignore")) {
    ACTSTYPES.push(ACTSDEFSROOT.childNodes[node].getAttribute("name"));
    ACTSRWDS.push(ACTSDEFSROOT.childNodes[node].getAttribute("rwd"));
    ACTSTRWDS.push(ACTSDEFSROOT.childNodes[node].getAttribute("trwd"));
  }
}


function LoadActions() {
  if(!dos_isfile(ACTSFILE)) {
    CreateActionsFile(ACTSFILE);
  } else {	
    ACTSDOM.load(ACTSFILE);
  }
  ACTSROOT=ACTSDOM.selectSingleNode("actions");
}

function SaveActions() {
  ACTSDOM.save(ACTSFILE);
}

function set_action_attr(id,attr,val) {
  var act=ACTSROOT.selectSingleNode("/actions/action[ @id=\""+id+"\"]");
  if(act) {
    act.setAttribute(attr,val);
  }
}

function get_action_attr(id,attr) {
  var act=ACTSROOT.selectSingleNode("/actions/action[ @id=\""+id+"\"]");
  if(act) {
    return act.getAttribute(attr);
  }
  return "";
}


function action_isfinal(ft) {
  return ft && ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("type")=="F";
}

function action_issearch(ft) {
  return ft && ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("type")=="S";
}

function action_isdead(ft) {
  return ft=="DEAD" || ft=="DEADE";
}


function action_defaultLDATE(ft) {
  return parseInt(ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("ldate"))*30;
}

function action_defaultRDATE(ft) {
  return parseInt(ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("rdate"))*30;
}

function action_defaultRWD(ft) {
  return parseFloat(ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("rwd"));
}

function action_defaultPAX(ft) {
  return parseFloat(ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("pax"));
}

function action_PaxWeight(ft) {
  return parseInt(ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("fpax"));
}
// date reference for limit date (pri or fi)
function action_defaultRefDate(ft) {
  return (ft && ACTSDEFSROOT.selectSingleNode("action[@name = \""+ft+"\"]").getAttribute("since")) || "";
}


function actionrwd(idx) {
  if(idx)  return ACTSRWDS[idx] ;
  return 0.0;
}



function CreateActionsFile() {
  ACTSROOT=ACTSDOM.createElement("actions");
  ACTSROOT.setAttribute("nextid","1");
  ACTSDOM.appendChild(ACTSROOT);
 
  ACTSDOM.save(ACTSFILE); 
}

function GetActionNextId() {
  return ACTSROOT.getAttribute("nextid");
}

function IncActionNextId() {
  ACTSROOT.setAttribute("nextid",parseInt(ACTSROOT.getAttribute("nextid"))+1);
}  

function UpdateLastAction(dn) {
  var nodes=ACTSROOT.selectNodes("/actions/action[ @dn=\""+dn+"\"]");
  var last=0;
  var lastid=0;
  if(nodes && nodes.length) {
    for(var i=0; i< nodes.length; i++) {
      if(parseInt(nodes[i].getAttribute("id")) > lastid) {
	lastid=parseInt(nodes[i].getAttribute("id"));
	last=i;
      }
      nodes[i].setAttribute("last","no");
    }
    nodes[last].setAttribute("last","yes");
  }
}

 
function FindLastAction(dn) {
  //alert("/actions/action[ @dn=\""+dn+"\" && @last=\"yes\"]");
  var node=ACTSROOT.selectNodes("/actions/action[ @dn=\""+dn+"\" && @last=\"yes\"]");
  return new actions_iterator(node);
}


function AddAction(dn,an,vers,type,rwd,trwd,limdate,donedate,replydate,pax) {
  //alert("AddAction "+type+" for "+dn);
  //return;
  var act=ACTSDOM.createElement("action");
  var ddate=normalizeDate(donedate)||"";
  var id=GetActionNextId();
  act.setAttribute("id",id);
 
  act.setAttribute("dn",dn||"");
  act.setAttribute("an",an||"");
  act.setAttribute("vers",vers||"");
  act.setAttribute("type",type||"");
  act.setAttribute("rwd",rwd||"0.0");
  act.setAttribute("trwd",trwd||"");
  act.setAttribute("ldate", normalizeDate(limdate)||"");
  act.setAttribute("ddate", ddate);
  act.setAttribute("rdate", normalizeDate(replydate)||"");
  act.setAttribute("pax",pax||"");

  act.setAttribute("last","yes");
  ACTSROOT.appendChild(act);
  IncActionNextId();  
  UpdateLastAction(dn);

  /* is not saved automatically, confusing
  if(action_isdead(type)) {
    SetDossierEndDate(ddate,dn);
  }
  */

  ACTSDOM.save(ACTSFILE);

  if(dn == GetDossierNumber()) {
    updatedossiercache();
  }
  return id;
}


function EditAction(id,dn,an,vers,type,rwd,trwd,limdate,donedate,replydate,pax) {
  var act=ACTSROOT.selectSingleNode("/actions/action[ @id=\""+id+"\"]");
  if(act) {
    var ddate=normalizeDate(donedate)||"";
    act.setAttribute("dn",dn||"");
    act.setAttribute("an",an||"");
    act.setAttribute("vers",vers||"");
    act.setAttribute("type",type||"");
    act.setAttribute("rwd",rwd||"0.0");
    act.setAttribute("trwd",trwd||"");
    act.setAttribute("ldate", normalizeDate(limdate)||"");
    act.setAttribute("ddate", ddate);
    act.setAttribute("rdate", normalizeDate(replydate)||"");
    act.setAttribute("pax",pax||"");
    UpdateLastAction(dn);
    /* is not saved automatically, confusing
    if(action_isdead(type)) {
      SetDossierEndDate(ddate,dn);
    }
    */
    ACTSDOM.save(ACTSFILE);
  }
}

function RemoveAction(id) {
  var act_iter= new actions_iterator(FindActions("id",id));
  if(!act_iter.end()) {
    ACTSROOT.removeChild(act_iter.getValue());
    ACTSDOM.save(ACTSFILE);
  } else {	
    alert("Cannot Remove, not found");
  }
}

// Sorting of actions 

// Sort using rwd 
function actionsortrwd(a,b) {
  return a.getAttribute("rwd") - b.getAttribute("rwd");
}
function antiactionsortrwd(a,b) {
  return b.getAttribute("rwd") - a.getAttribute("rwd");
}


function actionsortpax(a,b) {
  return (a.getAttribute("pax") || action_defaultPAX(a.getAttribute("type"))) - (b.getAttribute("pax") || action_defaultPAX(b.getAttribute("type")));
}

function antiactionsortpax(a,b) {
  return (b.getAttribute("pax")|| action_defaultPAX(b.getAttribute("type"))) - (a.getAttribute("pax") || action_defaultPAX(a.getAttribute("type")));
}


function actionsortxdate(attr,a,b) {
  if(!a.getAttribute(attr)) {
    return 1;
  }
  if(!b.getAttribute(attr)) {
    return -1;
  }
  return str2Date(a.getAttribute(attr)) - str2Date(b.getAttribute(attr));
}

function antiactionsortxdate(attr,a,b) {
  if(!a.getAttribute(attr)) {
    return 1;
  }
  if(!b.getAttribute(attr)) {
    return -1;
  }
  return str2Date(b.getAttribute(attr)) - str2Date(a.getAttribute(attr));
  //return !actionsortxdate(attr,a,b);
}

function actionsortalpha(attr,a,b) {
  //return a.getAttribute(attr) > b.getAttribute(attr);
  // alert("compare "+attr);
  var str1=a.getAttribute(attr);
  var str2=b.getAttribute(attr);
  //alert("compare "+attr+ " "+str1+" and "+str2);
  for(var i=0; i< str1.length && str2.length; i++) {
    if(str1.charAt(i) < str2.charAt(i)) {
      return -1;
    }
    if(str1.charAt(i) > str2.charAt(i)) {
      return 1;
    }
  }
  return str1.length-str2.length;
} 

function antiactionsortalpha(attr,a,b) {
  return actionsortalpha(attr,b,a);
} 

function actionsortddate(a,b) {
  return actionsortxdate("ddate",a,b);
}
function antiactionsortddate(a,b) {
  return antiactionsortxdate("ddate",a,b);
}

function actionsortldate(a,b) {
  return actionsortxdate("ldate",a,b);
}
function antiactionsortldate(a,b) {
  return antiactionsortxdate("ldate",a,b);
}

function actionsortrdate(a,b) {
  return actionsortxdate("rdate",a,b);
}

function antiactionsortrdate(a,b) {
  return antiactionsortxdate("rdate",a,b);
}

function actionsorttype(a,b) {
  return actionsortalpha("type",a,b);
}
function antiactionsorttype(a,b) {
  return antiactionsortalpha("type",a,b);
}

function actionsortdn(a,b) {
  return actionsortalpha("dn",a,b);
}
function antiactionsortdn(a,b) {
  return antiactionsortalpha("dn",a,b);
}

var _setactionsort=actionsortddate;

function SetSortActionFunct(f) {
  //alert("sort by "+f);
  switch(f) {
  case "rwd":
    if(_setactionsort==actionsortrwd) {
      _setactionsort=antiactionsortrwd;
    } else {
      _setactionsort=actionsortrwd;
    }      
    break;
  case "pax":
    if(_setactionsort==actionsortpax) {
      _setactionsort=antiactionsortpax;
    } else {
      _setactionsort=actionsortpax;
    }      
    break;

  case "ddate":
    if(_setactionsort==actionsortddate) {
      _setactionsort=antiactionsortddate;
    } else {
      _setactionsort=actionsortddate;
    }
    break;
  case "ldate":
    if(_setactionsort==actionsortldate) {
      _setactionsort=antiactionsortldate;
    } else {
      _setactionsort=actionsortldate;
    }
    break;
  case "rdate":
    if(_setactionsort==actionsortrdate) {
      _setactionsort=antiactionsortrdate;
    } else {
      _setactionsort=actionsortrdate;
    }
    break;    
  case "type":
    if(_setactionsort==actionsorttype) {
      _setactionsort=antiactionsorttype;
    } else {
      _setactionsort=actionsorttype;
    }
    break;
  case "dn":
    if(_setactionsort==actionsortdn) {
      _setactionsort=antiactionsortdn;
    } else {
      _setactionsort=actionsortdn;
    }
    break;
  }
}

function sortactions(actlist) {
  var lout= new Array();
   if(_setactionsort) {
     for(var n=0; n< actlist.length; n++) {
      lout.push(actlist[n]);
     }
     return lout.sort(_setactionsort);
   } else {
     return actlist;
   }
}
     

function FindMyActions() {
  return ACTSROOT.selectNodes("/actions/action[ @dn=\""+GetDossierNumber()+"\"]");
}

function FindMyActionsType(tag) {
  return ACTSROOT.selectNodes("/actions/action[ @dn=\""+GetDossierNumber()+"\" && @type=\""+tag+"\"] ");
}


function FindActions(field,val,field2,val2,field3,val3) {
  var actlist=""
  if(val3) {
    actlist=ACTSROOT.selectNodes("/actions/action[ @"+field+"=\""+val+"\" && @"+field2+"=\""+val2+"\" && @"+field3+"=\""+val3+"\"]");
  } else if(val2) {
    actlist=ACTSROOT.selectNodes("/actions/action[ @"+field+"=\""+val+"\" && @"+field2+"=\""+val2+"\"]");
  } else {   
    actlist=ACTSROOT.selectNodes("/actions/action[ @"+field+"=\""+val+"\"]");
  }
  
  return sortactions(actlist);
}


function FindOPActions(dn) {
  return FindActions("dn",dn,"type","OP");
}
 
function FindAllActions(year,month) {
  var actlist=ACTSROOT.childNodes;
  var lout= new Array();
  //var idate=str2Date("01/"+month+"/"+year);
  var _month=normalMonth(month);
  //alert("01/"+month+"/"+year);
  //alert("Found "+actlist.length);
  for(var a=0; a< actlist.length; a++) {
    var ddate=actlist[a].getAttribute("ddate").split("/");    
    var ldate=actlist[a].getAttribute("ldate").split("/");
    var rdate=actlist[a].getAttribute("rdate").split("/");    
       
    if(!ddate[0] && !ldate[0] && !rdate[0]) {
      lout.push(actlist[a]);
    } else {
      if(_month >0) {
	if( (ddate[0] && normalMonth(ddate[1])==_month && ddate[2]==year) || 
	    (ldate[0] && normalMonth(ldate[1])==_month && ldate[2]==year && !ddate[0]) ||
	    (rdate[0] && normalMonth(rdate[1])==_month && rdate[2]==year &&  ddate[0])) {
	  lout.push(actlist[a]);
	}
      } else if((ddate[0] && ddate[2]==year) || (ldate[0] && ldate[2]==year) || (rdate[0] && rdate[2]==year)) {
	lout.push(actlist[a]);
      }      
    }
  }
  if(_setactionsort) {
    return lout.sort(_setactionsort);
  }
  return lout;
}


function FindActionsDone(year,month) {
  //alert("FindActionsDone("+year+","+month+")");
  var actlist=ACTSROOT.selectNodes("/actions/action[ @ddate!=\"\"]");
  var lout= new Array();
  //var idate=str2Date("01/"+month+"/"+year);
  var _month=normalMonth(month);
  //alert("01/"+month+"/"+year);
  //alert("Found "+actlist.length);
  
   for(var a=0; a< actlist.length; a++) {
    var adate=actlist[a].getAttribute("ddate").split("/");    
    //if(adate[2]==year) alert(adate[2]+"=="+year+" "+parseInt(adate[1])+"=="+_month);
    if(adate[2]==year && (month==0 || normalMonth(adate[1])==_month)) {
      //alert("Add "+actlist[a].getAttribute("ddate"));
      lout.push(actlist[a]);
    } 
    //alert("next");
  }
  if(_setactionsort) {
    return lout.sort(_setactionsort);
  }
  return lout;
}

function FindActionsTodo() {
  return sortactions(ACTSROOT.selectNodes("/actions/action[ @ddate=\"\"]"));
}

function FindActionsTodie() {
  var actlist=ACTSROOT.selectNodes("/actions/action[ @ddate!=\"\" && @rdate!=\"\" && @last!=\"no\" ]");
  var lout= new Array();
  for(var n=0; n< actlist.length; n++) {
    if(!action_isfinal(actlist[n].getAttribute("type"))){
      lout.push(actlist[n]);
    }
  }
  return lout.sort(_setactionsort);
}

// DEAD  -> update
// DEADE -> update
// FINAL or PCT -> DEADE
// not final and EPC ->DEAD
function SetActionDead(dn,_ddate) {
  var ddate=normalizeDate(_ddate);
  var actlast=ACTSROOT.selectSingleNode("/actions/action[ @dn=\""+dn+"\" && @last!=\"no\" ]");
  if(actlast) { // found last action 
    switch(actlast.getAttribute("type")) {
    case "DEAD":
    case "DEADE":
      EditAction(actlast.getAttribute("id"),
		 dn,actlast.getAttribute("an"),
		 actlast.getAttribute("vers"),
		 actlast.getAttribute("type"),
		 actlast.getAttribute("rwd"),
		 "",
		 "",
		 ddate);
      break;
    case "SR":
    case "SR-NU":
      AddAction(dn,actlast.getAttribute("an"),actlast.getAttribute("vers"),"DEADE","0.0","","",ddate);
      break;
    default:
      
      if(action_isfinal(actlast.getAttribute("type")) || actlast.getAttribute("phase")!="EPC") {
	AddAction(dn,actlast.getAttribute("an"),actlast.getAttribute("vers"),"DEADE","0.0","","",ddate);
      } else {
	AddAction(dn,actlast.getAttribute("an"),actlast.getAttribute("vers"),"DEAD",
		  action_defaultRWD("DEAD"),"","",ddate);
      }
    }
  } else {
    //alert("Add DEAD to "+dn);
    AddAction(dn,dn,1,"DEAD",action_defaultRWD("DEAD"),"","",ddate);
  }
}
  

function action_searches(actlist) {
  var tmp=0;
  for(a in actlist) {
    if(action_issearch(actlist[a].getAttribute("type"))) {
      tmp++;
    }
  }
  return tmp;
}

function action_final(actlist) {
  var tmp=0;
  for(a in actlist) {
    if(action_isfinal(actlist[a].getAttribute("type"))) {
      tmp++;
    }
  }
  return tmp;
}

function action_rwd(actlist) {
  var tmp=0.0;
  for(a in actlist) {
    tmp+=parseFloat(actlist[a].getAttribute("rwd"));
  }
  return tmp;
}

function action_get_phase(atype) {
  return ACTSDEFSROOT.selectSingleNode("/actions/action[ @name=\""+atype+"\" ]").getAttribute("phase");
}

//------------------------------------------------------------------------------------
// Actions iterator 
//------------------------------------------------------------------------------------

function actions_iterator(actlist) {
  this._actlist=actlist||"";
  this._idx=0;
  this._end=actlist.length||0;
}


actions_iterator.prototype.end = function() {return this._idx>= this._end;}
actions_iterator.prototype.next = function() { this._idx++ ;}
actions_iterator.prototype.getID = function () { return this._actlist[this._idx].getAttribute("id");} 
actions_iterator.prototype.getDN = function() { return this._actlist[this._idx].getAttribute("dn");} 
actions_iterator.prototype.getAN = function() { return this._actlist[this._idx].getAttribute("an");} 
actions_iterator.prototype.getVERS = function() { return this._actlist[this._idx].getAttribute("vers") || "";} 
actions_iterator.prototype.getTYPE = function() { return this._actlist[this._idx].getAttribute("type") || "";} 
actions_iterator.prototype.getRWD = function() { return this._actlist[this._idx].getAttribute("rwd") || "";}
actions_iterator.prototype.getTRWD = function() { return this._actlist[this._idx].getAttribute("trwd") || "";}

actions_iterator.prototype.getAttr = function(tag) { return this._actlist[this._idx].getAttribute(tag) || "";}
actions_iterator.prototype.setAttr = function(tag,val) { return this._actlist[this._idx].setAttribute(tag,val);}

actions_iterator.prototype.getLDATE = function() { return normalizeDate(this._actlist[this._idx].getAttribute("ldate"));}
actions_iterator.prototype.getDDATE = function() { return normalizeDate(this._actlist[this._idx].getAttribute("ddate"));} 
actions_iterator.prototype.getRDATE = function() { return normalizeDate(this._actlist[this._idx].getAttribute("rdate"));}   
actions_iterator.prototype.getPAX = function()   { return this._actlist[this._idx].getAttribute("pax") 
			       || action_defaultPAX(this.getTYPE())}   
actions_iterator.prototype.getField= function (field) { return this._actlist[this._idx].getAttribute(field) || 0;} 
actions_iterator.prototype.getValue = function() { return this._actlist[this._idx];}    
actions_iterator.prototype.is_final = function() { return action_isfinal(this.getTYPE());  }
actions_iterator.prototype.is_last = function () { return this._actlist[this._idx].getAttribute("last")!="no"; }
actions_iterator.prototype.is_search = function () { return action_issearch(this.getTYPE());}
actions_iterator.prototype.getDefaultLDATE = function() { return action_defaultLDATE(this.getTYPE()); }
actions_iterator.prototype.getDefaultRDATE = function() { return action_defaulRLDATE(this.getTYPE()); }
actions_iterator.prototype.getPaxWeight = function () {  return action_PaxWeight(this.getTYPE());}



